#!/bin/bash
# MySQL初始化脚本 - 使用环境变量

# 检查必需的环境变量
if [ -z "$MYSQL_USER" ]; then
    echo "错误: MYSQL_USER 环境变量未设置"
    exit 1
fi

if [ -z "$MYSQL_PASSWORD" ]; then
    echo "错误: MYSQL_PASSWORD 环境变量未设置"
    exit 1
fi

# 生成SQL脚本
cat > /docker-entrypoint-initdb.d/init.sql << EOF
-- 初始化MySQL数据库脚本

-- 创建用户
CREATE USER IF NOT EXISTS '${MYSQL_USER}'@'%' IDENTIFIED WITH mysql_native_password BY '${MYSQL_PASSWORD}';

-- 创建生产环境数据库
CREATE DATABASE IF NOT EXISTS xbyjob CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 创建开发环境数据库
CREATE DATABASE IF NOT EXISTS xbyjob_dev CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 创建测试环境数据库
CREATE DATABASE IF NOT EXISTS xbyjob_test CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 授权用户访问数据库
GRANT ALL PRIVILEGES ON xbyjob.* TO '${MYSQL_USER}'@'%';
GRANT ALL PRIVILEGES ON xbyjob_dev.* TO '${MYSQL_USER}'@'%';
GRANT ALL PRIVILEGES ON xbyjob_test.* TO '${MYSQL_USER}'@'%';

-- 刷新权限
FLUSH PRIVILEGES;
EOF

echo "MySQL初始化脚本已生成"